package com.chookss.tiku

import android.os.Bundle
import android.view.View
import android.widget.CheckBox
import androidx.appcompat.app.ActionBarDrawerToggle
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProviders
import com.chookss.R
import com.chookss.tiku.entity.CanSignExam
import com.johnrambo.ktea.common.createLoadingDialog
import errorToast
import kotlinx.android.synthetic.main.activity_sign_exam.*
import successToast

/**
 * Company:
 * Project:
 * Author: liuhaoge
 * Date: 2021/1/8 8:45
 * Note: 申请考试报名
 */
class SignExamActivity : AppCompatActivity() {

    val viewModel by lazy {
        ViewModelProviders.of(this).get(SignExamViewModel::class.java)
    }
    protected val loadingProgress by lazy {
        createLoadingDialog(this) {}
    }
    val selectCodes = ArrayList<String>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_sign_exam)

        val toggle = ActionBarDrawerToggle(
                this, drawer_layout, null, 0, 0)
        drawer_layout.addDrawerListener(toggle)
        toggle.syncState()

        viewModel.getCanSignExams().observe(this, {
            if (it.error != null) {
                errorToast(it.error.message ?: "")
            } else if (it.data?.size?:0 > 0) {
                updateItemsView(it.data!!)
            } else {
                errorToast("没有数据")
            }
        })

        btnSelect.setOnClickListener {
            drawer_layout.openDrawer(drawerMenu)
        }

        btnOk.setOnClickListener {
            drawer_layout.closeDrawer(drawerMenu)
            updateSelect()
        }

        btnSubmit.setOnClickListener {
            submitSignUp()
        }
    }

    private fun updateSelect() {
        selectCodes.clear()
        var list = ArrayList<String>()
        for (i in 0 until llItems.childCount) {
            var cb = llItems.getChildAt(i) as CheckBox
            if (cb.isChecked) {
                selectCodes.add(cb.tag as String)
                list.add(cb.text as String)
            }
        }
        tvSelect.text = list.joinToString(",")
    }

    private fun submitSignUp() {
        if (selectCodes.isEmpty()) {
            errorToast("请选择要报名的考试")
            return
        }
        loadingProgress.show()
        viewModel.signUp(selectCodes.joinToString(",")).observe(this, {
            loadingProgress.dismiss()
            if (it.error != null) {
                errorToast(it.error.message ?: "")
            } else {
                successToast("考试申请成功,请注意查看考试通知")
                finish()
            }
        })
    }

    private fun updateItemsView(data: List<CanSignExam>) {
        data.forEach {
            View.inflate(this, R.layout.item_signup_exam, llItems)
            var cb = llItems.getChildAt(llItems.childCount - 1) as CheckBox
            cb.text = it.examSignName
            cb.tag = it.examSignCode
        }
    }
}